package com.toy.core.security.access.voter;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.toy.core.config.SysConfig;
import com.toy.core.security.Authentication;
import com.toy.core.security.chain.FilterInvocation;
import com.toy.core.security.exception.AuthenticationException;

public class PublicAccessDecisionVoter implements AccessDecisionVoter {
	
	@Autowired
	private SysConfig sysConfig;
	
	public int vote(Authentication authentication,
			FilterInvocation filterInvocation) {
		if ( isPublicURL(filterInvocation) ){
			//可以匿名访问
			return ACCESS_GRANTED;
		}else{
			if ( authentication == null ){
				//该url需要登陆
				throw new AuthenticationException(AuthenticationException.CODE_InsufficientAuthenticationException);
			}else{
				//对已登录用户保持中立
				return ACCESS_ABSTAIN;
			}
		}
		
	}
	
	private boolean isPublicURL(FilterInvocation fi) {
		List<String> urlPatterns = sysConfig.getPublicUrls();
		for (Iterator<String> iter = urlPatterns.iterator(); iter.hasNext();) {
			String pattern = iter.next();
			if (fi != null && ( fi.getRequestUrl().startsWith(pattern) 
					|| fi.getRequestUrl().startsWith(fi.getHttpRequest().getContextPath()+pattern))) {
				return true;
			}
		}
		return false;
	}
}
